home *** CD-ROM | disk | FTP | other *** search
/ Libris Britannia 4 / science library(b).zip / science library(b) / CUGUK / COMMS / C100.ZIP / KERMIT.ZIP / CKXFIO.C < prev    next >
Text File  |  1990-01-31  |  31KB  |  1,107 lines

  1. char *ckzv = "Unix file support, 4E(037) 27 Jan 88";
  2.  
  3. /* C K U F I O  --  Kermit file system support for Unix systems */
  4.  
  5. /* 4E, conditionals added for Apollo Aegis, MINIX */
  6.  
  7. /*
  8.  Author: Frank da Cruz (SY.FDC@CU20B),
  9.  Columbia University Center for Computing Activities, January 1985.
  10.  Copyright (C) 1985, Trustees of Columbia University in the City of New York.
  11.  Permission is granted to any individual or institution to use, copy, or
  12.  redistribute this software so long as it is not sold for profit, provided this
  13.  copyright notice is retained.
  14. */
  15. /* Includes */
  16.  
  17. #include <sys/types.h>            /* Data types */
  18. #include "ckcker.h"            /* Kermit definitions */
  19. #include "ckcdeb.h"            /* Typedefs, debug formats, etc */
  20. #include <ctype.h>            /* Character types */
  21. #include <stdio.h>            /* Standard i/o */
  22. #include <sys/dir.h>            /* Directory structure */
  23. #include <pwd.h>            /* Password file for shell name */
  24.  
  25. #ifdef CIE
  26. #include <stat.h>            /* File status */
  27. #else
  28. #include <sys/stat.h>
  29. #endif
  30.  
  31.  
  32. /* Berkeley Unix Version 4.x */
  33. /* 4.1bsd support added by Charles E Brooks, EDN-VAX */
  34.  
  35. #ifdef BSD4
  36. #ifdef MAXNAMLEN
  37. #define BSD42
  38. char *ckzsys = " 4.2 BSD";
  39. #else
  40. #ifdef FT18
  41. #define BSD41
  42. char *ckzsys = " Fortune For:Pro 1.8";
  43. #else
  44. #define BSD41
  45. char *ckzsys = " 4.1 BSD";
  46. #endif
  47. #endif
  48. #endif
  49.  
  50. /* 2.9bsd support contributed by Bradley Smith, UCLA */
  51. #ifdef BSD29
  52. char *ckzsys = " 2.9 BSD";
  53. #endif
  54.  
  55. /* Version 7 Unix  */
  56. #ifdef V7
  57. #ifndef MINIX
  58. char *ckzsys = " Version 7 Unix";
  59. #else
  60. /* MINIX modifications : conditionals added by A Godwin 28.4.88 */
  61. char *ckzsys = " MINIX 1.1";
  62. #endif
  63. #endif
  64.  
  65. /* DEC Professional-300 series with Venturcom Venix v1 */
  66. #ifdef PROVX1
  67. char *ckzsys = " DEC Pro-3xx/Venix v1";
  68. #endif
  69.  
  70. /* NCR Tower support contributed by John Bray, Auburn, AL. */
  71. /* Tower OS is like Sys III but with BSD features -- mostly follows BSD. */
  72. #ifdef TOWER1
  73. char *ckzsys = " NCR Tower 1632, OS 1.02";
  74. #endif
  75.  
  76. /* Sys III/V, Xenix, PC/IX,... support by Herm Fischer, Litton Data Systems */
  77. #ifdef UXIII
  78. #ifdef XENIX
  79. char *ckzsys = " Xenix/286";
  80. #else
  81. #ifdef PCIX
  82. char *ckzsys = " PC/IX";
  83. #else
  84. #ifdef ISIII
  85. char *ckzsys = " Interactive Systems Corp, System III";
  86. #else
  87. #ifdef ZILOG
  88. char *ckzsys = " Zilog S8000 Zeus 3.21+";
  89. #else
  90. char *ckzsys = " AT&T System III/System V";
  91. #endif
  92. #endif
  93. #endif
  94. #endif
  95. #endif
  96.  
  97. /* Definitions of some Unix system commands */
  98.  
  99. char *DELCMD = "rm -f ";        /* For file deletion */
  100. char *PWDCMD = "pwd ";            /* For saying where I am */
  101.  
  102. #ifdef FT18
  103. char *DIRCMD = "ls -l | more ";        /* For directory listing */
  104. char *TYPCMD = "more ";            /* For typing a file */
  105. #else
  106. char *TYPCMD = "cat ";            /* For typing a file */
  107. char *DIRCMD = "ls -l ";        /* For directory listing */
  108. #endif
  109.  
  110. #ifdef FT18
  111. #undef BSD4
  112. #endif
  113.  
  114. #ifdef BSD4
  115. char *SPACMD = "pwd ; quota ; df .";    /* Space/quota of current directory */
  116. #else
  117. #ifdef FT18
  118. char #SPACMD = "pwd ; du ; df .";
  119. #else
  120. char *SPACMD = "df ";
  121. #endif
  122. #endif
  123.  
  124. char *SPACM2 = "df ";            /* For space in specified directory */
  125.  
  126. #ifdef FT18
  127. #define BSD4
  128. #endif
  129.  
  130. #ifdef BSD4
  131. char *WHOCMD = "finger ";        /* For seeing who's logged in */
  132. #else
  133. char *WHOCMD = "who ";            /* For seeing who's logged in */
  134. #endif
  135.  
  136. /*
  137.   Functions (n is one of the predefined file numbers from ckermi.h):
  138.  
  139.    zopeni(n,name)   -- Opens an existing file for input.
  140.    zopeno(n,name)   -- Opens a new file for output.
  141.    zclose(n)        -- Closes a file.
  142.    zchin(n,&c)      -- Gets the next character from an input file.
  143.    zsout(n,s)       -- Write a null-terminated string to output file, buffered.
  144.    zsoutl(n,s)      -- Like zsout, but appends a line terminator.
  145.    zsoutx(n,s,x)    -- Write x characters to output file, unbuffered.
  146.    zchout(n,c)      -- Add a character to an output file, unbuffered.
  147.    zchki(name)      -- Check if named file exists and is readable, return size.
  148.    zchko(name)      -- Check if named file can be created.
  149.    znewn(name,s)    -- Make a new unique file name based on the given name.
  150.    zdelet(name)     -- Delete the named file.
  151.    zxpand(string)   -- Expands the given wildcard string into a list of files.
  152.    znext(string)    -- Returns the next file from the list in "string".
  153.    zxcmd(cmd)       -- Execute the command in a lower fork.
  154.    zclosf()         -- Close input file associated with zxcmd()'s lower fork.
  155.    zrtol(n1,n2)     -- Convert remote filename into local form.
  156.    zltor(n1,n2)     -- Convert local filename into remote form.
  157.    zchdir(dirnam)   -- Change working directory.
  158.    zhome()          -- Return pointer to home directory name string.
  159.    zkself()         -- Kill self, log out own job.
  160.  */
  161.  
  162. #ifdef FT18
  163. #define PROVX1
  164. #endif
  165.  
  166. /* Which systems include <sys/file.h>... */
  167. #ifndef PROVX1
  168. #ifndef aegis
  169. #ifndef CIE
  170. #ifndef XENIX
  171. #ifndef MINIX
  172. /* Watch out, some versions of Xenix might need to do this include, */
  173. /* but reportedly SCO Xenix 2.2 on an 80x86 system does not. */
  174. #include <sys/file.h>            /* File access */
  175. #endif
  176. #endif
  177. #endif
  178. #endif
  179. #endif
  180.  
  181. #ifdef FT18
  182. #undef PROVX1
  183. #endif
  184.  
  185. /* Some systems define these symbols in include files, others don't... */
  186. #ifndef R_OK
  187. #define R_OK 4                /* For access */
  188. #endif
  189.  
  190. #ifndef W_OK
  191. #define W_OK 2
  192. #endif
  193.  
  194. #ifdef PROVX1
  195. #define MAXNAMLEN DIRSIZ        /* Max file name length */
  196. #endif
  197.  
  198. #ifdef UXIII
  199. #include <fcntl.h>
  200. #define MAXNAMLEN DIRSIZ
  201. #endif
  202.  
  203. #ifndef O_RDONLY
  204. #define O_RDONLY 000
  205. #endif
  206.  
  207. #ifndef MAXNAMLEN
  208. #define MAXNAMLEN 14            /* If still not defined... */
  209. #endif
  210.  
  211. #ifdef PROVX1
  212. #define MAXWLD 50            /* Maximum wildcard filenames */
  213. #else
  214. #ifdef BSD29
  215. #define MAXWLD 50            /* Maximum wildcard filenames */
  216. #else
  217. #define MAXWLD 500
  218. #endif
  219. #endif
  220.  
  221. /* Declarations */
  222.  
  223. FILE *fp[ZNFILS] = {             /* File pointers */
  224.     NULL, NULL, NULL, NULL, NULL, NULL, NULL };
  225.  
  226. static int pid;                    /* pid of child fork */
  227. static int fcount;            /* Number of files in wild group */
  228. static char nambuf[MAXNAMLEN+2];    /* Buffer for a filename */
  229. char *malloc(), *getenv(), *strcpy();    /* System functions */
  230. extern errno;                /* System error code */
  231.  
  232. static char *mtchs[MAXWLD],        /* Matches found for filename */
  233.      **mtchptr;                /* Pointer to current match */
  234.  
  235. /*  Z K S E L F  --  Kill Self: log out own job, if possible.  */
  236.  
  237. /* Note, should get current pid, but if your system doesn't have */
  238. /* getppid(), then just kill(0,9)...  */
  239.  
  240. zkself() {                /* For "bye", but no guarantee! */
  241. #ifdef PROVX1
  242.     return(kill(0,9));
  243. #else
  244. #ifdef V7
  245.     return(kill(0,9));
  246. #else
  247. #ifdef TOWER1
  248.     return(kill(0,9));
  249. #else
  250. #ifdef FT18
  251.     return(kill(0,9));
  252. #else
  253. #ifdef aegis
  254.     return(kill(0,9));
  255. #else
  256.     return(kill(getppid(),1));
  257. #endif
  258. #endif
  259. #endif
  260. #endif
  261. #endif
  262. }
  263.  
  264. /*  Z O P E N I  --  Open an existing file for input. */
  265.  
  266. zopeni(n,name) int n; char *name; {
  267.     debug(F111," zopeni",name,n);
  268.     debug(F101,"  fp","",(int) fp[n]);
  269.     if (chkfn(n) != 0) return(0);
  270.     if (n == ZSYSFN) {            /* Input from a system function? */
  271.         debug(F110," invoking zxcmd",name,0);
  272.     return(zxcmd(name));        /* Try to fork the command */
  273.     }
  274.     if (n == ZSTDIO) {            /* Standard input? */
  275.     if (isatty(0)) {
  276.         ermsg("Terminal input not allowed");
  277.         debug(F110,"zopeni: attempts input from unredirected stdin","",0);
  278.         return(0);
  279.     }
  280.     fp[ZIFILE] = stdin;
  281.     return(1);
  282.     }
  283.     fp[n] = fopen(name,"r");        /* Real file. */
  284.     debug(F111," zopeni", name, (int) fp[n]);
  285.     if (fp[n] == NULL) perror("zopeni");
  286.     return((fp[n] != NULL) ? 1 : 0);
  287. }
  288.  
  289. /*  Z O P E N O  --  Open a new file for output.  */
  290.  
  291. zopeno(n,name) int n; char *name; {
  292.     debug(F111," zopeno",name,n);
  293.     if (chkfn(n) != 0) return(0);
  294.     if ((n == ZCTERM) || (n == ZSTDIO)) {   /* Terminal or standard output */
  295.     fp[ZOFILE] = stdout;
  296.     debug(F101," fp[]=stdout", "", (int) fp[n]);
  297.     return(1);
  298.     }
  299.     fp[n] = fopen(name,"w");        /* A real file, try to open */
  300.     if (fp[n] == NULL) {
  301.         perror("zopeno can't open");
  302.     } else {
  303.     chown(name, getuid(), getgid());     /* In case set[gu]id */
  304.         if (n == ZDFILE) setbuf(fp[n],NULL); /* Debugging file unbuffered */
  305.     }
  306.     debug(F101, " fp[n]", "", (int) fp[n]);
  307.     return((fp[n] != NULL) ? 1 : 0);
  308. }
  309.  
  310. /*  Z C L O S E  --  Close the given file.  */
  311.  
  312. /*  Returns 0 if arg out of range, 1 if successful, -1 if close failed.  */
  313.  
  314. zclose(n) int n; {
  315.     int x;
  316.     if (chkfn(n) < 1) return(0);    /* Check range of n */
  317.     if ((n == ZIFILE) && fp[ZSYSFN]) {    /* If system function */
  318.         x = zclosf();            /* do it specially */
  319.     } else {
  320.         if ((fp[n] != stdout) && (fp[n] != stdin)) x = fclose(fp[n]);
  321.     fp[n] = NULL;
  322.     }
  323.     return((x == EOF) ? -1 : 1);
  324. }
  325.  
  326. /*  Z C H I N  --  Get a character from the input file.  */
  327.  
  328. /*  Returns -1 if EOF, 0 otherwise with character returned in argument  */
  329.  
  330. zchin(n,c) int n; char *c; {
  331.     int a;
  332.     if (chkfn(n) < 1) return(-1);
  333.     a = getc(fp[n]);
  334.     if (a == EOF) return(-1);
  335.     *c = a & 0377;
  336.     return(0);
  337. }
  338.  
  339. /*  Z S O U T  --  Write a string to the given file, buffered.  */
  340.  
  341. zsout(n,s) int n; char *s; {
  342.     if (chkfn(n) < 1) return(-1);
  343.     fputs(s,fp[n]);
  344.     return(0);
  345. }
  346.  
  347. /*  Z S O U T L  --  Write string to file, with line terminator, buffered  */
  348.  
  349. zsoutl(n,s) int n; char *s; {
  350.     if (chkfn(n) < 1) return(-1);
  351.     fputs(s,fp[n]);
  352.     fputs("\n",fp[n]);
  353.     return(0);
  354. }
  355.  
  356. /*  Z S O U T X  --  Write x characters to file, unbuffered.  */
  357.  
  358. zsoutx(n,s,x) int n, x; char *s; {
  359.     if (chkfn(n) < 1) return(-1);
  360. /*  return(write(fp[n]->_file,s,x));  */
  361.     return(write(fileno(fp[n]),s,x));
  362. }
  363.  
  364.  
  365. /*  Z C H O U T  --  Add a character to the given file.  */
  366.  
  367. /*  Should return 0 or greater on success, -1 on failure (e.g. disk full)  */
  368.  
  369. zchout(n,c) int n; char c; {
  370.     if (chkfn(n) < 1) return(-1);
  371.     if (n == ZSFILE)
  372.         return(write(fileno(fp[n]),&c,1)); /* Use unbuffered for session log */
  373.     else {                /* Buffered for everything else */
  374.     if (putc(c,fp[n]) == EOF)    /* If true, maybe there was an error */
  375.         return(ferror(fp[n])?-1:0);    /* Check to make sure */
  376.     else                /* Otherwise... */
  377.         return(0);            /* There was no error. */
  378.     }
  379. }
  380.  
  381. /*  C H K F N  --  Internal function to verify file number is ok  */
  382.  
  383. /*
  384.  Returns:
  385.   -1: File number n is out of range
  386.    0: n is in range, but file is not open
  387.    1: n in range and file is open
  388. */
  389. chkfn(n) int n; {
  390.     switch (n) {
  391.     case ZCTERM:
  392.     case ZSTDIO:
  393.     case ZIFILE:
  394.     case ZOFILE:
  395.     case ZDFILE:
  396.     case ZTFILE:
  397.     case ZPFILE:
  398.     case ZSFILE:
  399.     case ZSYSFN: break;
  400.     default:
  401.         debug(F101,"chkfn: file number out of range","",n);
  402.         fprintf(stderr,"?File number out of range - %d\n",n);
  403.         return(-1);
  404.     }
  405.     return( (fp[n] == NULL) ? 0 : 1 );
  406. }
  407.  
  408. /*  Z C H K I  --  Check if input file exists and is readable  */
  409.  
  410. /*
  411.   Returns:
  412.    >= 0 if the file can be read (returns the size).
  413.      -1 if file doesn't exist or can't be accessed,
  414.      -2 if file exists but is not readable (e.g. a directory file).
  415.      -3 if file exists but protected against read access.
  416. */
  417. /*
  418.  For Berkeley Unix, a file must be of type "regular" to be readable.
  419.  Directory files, special files, and symbolic links are not readable.
  420. */
  421. long
  422. zchki(name) char *name; {
  423.     struct stat buf;
  424.     int x; long y;
  425.  
  426.     x = stat(name,&buf);
  427.     if (x < 0) {
  428.     debug(F111,"zchki stat fails",name,errno);
  429.     return(-1);
  430.     }
  431.     x = buf.st_mode & S_IFMT;        /* Isolate file format field */
  432.     if ((x != 0) && (x != S_IFREG)) {
  433.     debug(F111,"zchki skipping:",name,x);
  434.     return(-2);
  435.     }
  436.     debug(F111,"zchki stat ok:",name,x);
  437.  
  438.     if ((x = access(name,R_OK)) < 0) {     /* Is the file accessible? */
  439.     debug(F111," access failed:",name,x); /* No */
  440.         return(-3);            
  441.     } else {
  442.     y = buf.st_size;
  443.     debug(F111," access ok:",name,(int) y); /* Yes */
  444.     return( (y > -1) ? y : 0 );
  445.     }
  446. }
  447.  
  448. /*  Z C H K O  --  Check if output file can be created  */
  449.  
  450. /*
  451.  Returns -1 if write permission for the file would be denied, 0 otherwise.
  452. */
  453. zchko(name) char *name; {
  454.     int i, x;
  455.     char s[50], *sp;    
  456.  
  457.     sp = s;                /* Make a copy, get length */
  458.     x = 0;
  459.     while ((*sp++ = *name++) != '\0')
  460.         x++;
  461.     if (x == 0) return(-1);        /* If no filename, fail. */
  462.  
  463.     debug(F101," length","",x);
  464.     for (i = x; i > 0; i--)        /* Strip filename. */
  465.     if (s[i-1] == '/') break;
  466.  
  467.     debug(F101," i","",i);
  468.     if (i == 0)                /* If no path, use current directory */
  469.         strcpy(s,"./");            
  470.     else                /* Otherwise, use given one. */
  471.         s[i] = '\0';
  472.  
  473.     x = access(s,W_OK);            /* Check access of path. */
  474.     if (x < 0) {
  475.     debug(F111,"zchko access failed:",s,errno);
  476.     return(-1);
  477.     } else {
  478.     debug(F111,"zchko access ok:",s,x);
  479.     return(0);
  480.     }
  481. }
  482.  
  483. /*  Z D E L E T  --  Delete the named file.  */
  484.  
  485. zdelet(name) char *name; {
  486.     unlink(name);
  487. }
  488.  
  489.  
  490. /*  Z R T O L  --  Convert remote filename into local form  */
  491.  
  492. /*  For UNIX, this means changing uppercase letters to lowercase.  */
  493.  
  494. zrtol(name,name2) char *name, *name2; {
  495.     for ( ; *name != '\0'; name++) {
  496.         *name2++ = isupper(*name) ? tolower(*name) : *name;
  497.     }
  498.     *name2 = '\0';
  499.     debug(F110,"zrtol:",name2,0);
  500. }
  501.  
  502.  
  503. /*  Z L T O R  --  Local TO Remote */
  504.  
  505. /*  Convert filename from local format to common (remote) form.  */
  506.  
  507. zltor(name,name2) char *name, *name2; {
  508.     char work[100], *cp, *pp;
  509.     int dc = 0;
  510. #ifdef aegis
  511.     char *getenv(), *index(), *namechars;
  512.     int tilde = 0, bslash = 0;
  513.  
  514.     if ((namechars = getenv("NAMECHARS")) != NULL) {
  515.         if (index(namechars, '~' ) != NULL) tilde  = '~';
  516.         if (index(namechars, '\\') != NULL) bslash = '\\';
  517.     } else {
  518.         tilde = '~';
  519.         bslash = '\\';
  520.     }
  521. #endif
  522.  
  523.     debug(F110,"zltor",name,0);
  524.     pp = work;
  525. #ifdef aegis
  526.     cp = name;
  527.     if (tilde && *cp == tilde)
  528.         ++cp;
  529.     for (; *cp != '\0'; cp++) {    /* strip path name */
  530.         if (*cp == '/' || *cp == bslash) {
  531. #else
  532.     for (cp = name; *cp != '\0'; cp++) {    /* strip path name */
  533.         if (*cp == '/') {
  534. #endif
  535.         dc = 0;
  536.         pp = work;
  537.     }
  538.     else if (islower(*cp)) *pp++ = toupper(*cp); /* Uppercase letters */
  539.     else if (*cp == '~') *pp++ = 'X';    /* Change tilde to 'X' */
  540.     else if (*cp == '#') *pp++ = 'X';    /* Change number sign to 'X' */
  541.     else if ((*cp == '.') && (++dc > 1)) *pp++ = 'X'; /* & extra dots */
  542.     else *pp++ = *cp;
  543.     }
  544.     *pp = '\0';                /* Tie it off. */
  545.     cp = name2;                /* If nothing before dot, */
  546.     if (*work == '.') *cp++ = 'X';    /* insert 'X' */
  547.     strcpy(cp,work);
  548.     debug(F110," name2",name2,0);
  549. }
  550.  
  551.  
  552. /*  Z C H D I R  --  Change directory  */
  553.  
  554. zchdir(dirnam) char *dirnam; {
  555.     char *hd;
  556.     if (*dirnam == '\0') hd = getenv("HOME");
  557.     else hd = dirnam;
  558.     return((chdir(hd) == 0) ? 1 : 0);
  559. }
  560.  
  561.  
  562. /*  Z H O M E  --  Return pointer to user's home directory  */
  563.  
  564. char *
  565. zhome() {
  566.     return(getenv("HOME"));
  567. }
  568.  
  569. /*  Z G T D I R  --  Return pointer to user's current directory  */
  570.  
  571. char *
  572. zgtdir() {
  573.  
  574. #ifdef MAXPATHLEN
  575. #define CWDBL MAXPATHLEN
  576. #else
  577. #define CWDBL 100
  578. #endif
  579.  
  580. #ifdef UXIII
  581.     char cwdbuf[CWDBL+1];
  582.     char *buf;
  583.     char *getcwd();
  584.     buf = cwdbuf;
  585.     return(getcwd(buf,CWDBL));
  586. #else
  587. #ifdef BSD4
  588.     char cwdbuf[CWDBL+1];
  589.     char *buf;
  590.     char *getwd();
  591.     buf = cwdbuf;
  592.     return(getwd(buf));
  593. #else
  594.     return("(directory unknown)");
  595. #endif
  596. #endif
  597. }
  598.  
  599. /*  Z X C M D -- Run a system command so its output can be read like a file */
  600.  
  601. zxcmd(comand) char *comand; {
  602.     int pipes[2];
  603.     if (pipe(pipes) != 0) {
  604.     debug(F100,"zxcmd pipe failure","",0);
  605.     return(0);            /* can't make pipe, fail */
  606.     }
  607. #ifdef aegis
  608.     if ((pid = vfork()) == 0) {        /* child */
  609. #else
  610.     if ((pid = fork()) == 0) {        /* child */
  611. #endif
  612.  
  613.  
  614. /*#if BSD4*/        /* Code from Dave Tweten@AMES-NAS */
  615.             /* readapted to use getpwuid to find login shell */
  616.             /*   -- H. Fischer */
  617.     char *shpath, *shname, *shptr;    /* to find desired shell */
  618. #ifndef aegis
  619.     struct passwd *p;
  620.     extern struct passwd * getpwuid();
  621.     extern int getuid();
  622.     char *defShel = "/bin/sh";    /* default shell */
  623. #endif
  624.  
  625.     close(pipes[0]);        /* close input side of pipe */
  626.     close(0);            /* close stdin */
  627.     if (open("/dev/null",0) < 0) return(0);    /* replace input by null */
  628.  
  629. #ifndef UXIII
  630.     dup2(pipes[1],1);        /* replace stdout & stderr */
  631.     dup2(pipes[1],2);        /* by the pipe */
  632. #else
  633.     close(1);            /* simulate dup2 */
  634.     if (dup(pipes[1]) != 1 )
  635.         conol("trouble duping stdout in routine zxcmd\n");
  636.     close(2);            /* simulate dup2 */
  637.     if (dup(pipes[1]) != 2 )
  638.         conol("trouble duping stderr in routine zxcmd\n");
  639. #endif
  640.  
  641.     close(pipes[1]);        /* get rid of this copy of the pipe */
  642.  
  643. #ifdef aegis
  644.     if ((shpath = getenv("SERVERSHELL")) == NULL) shpath = "/bin/sh";
  645. #else
  646.  
  647. /****     shptr = shname = shpath = getenv("SHELL");  /* What shell? */
  648.     p = getpwuid( getuid() );    /* get login data */
  649.     if ( p == (struct passwd *) NULL || !*(p->pw_shell) ) shpath = defShel;
  650.       else shpath = p->pw_shell;
  651. #endif
  652.     shptr = shname = shpath;
  653.     while (*shptr != '\0') if (*shptr++ == '/') shname = shptr;
  654.     debug(F100,"zxcmd...","",0);
  655.     debug(F110,shpath,shname,0);
  656.  
  657. /* Remove the following uid calls if they cause trouble... */
  658. #ifdef BSD4
  659.     setegid(getgid());        /* Override 4.3BSD csh */
  660.     seteuid(getuid());        /*  security checks */
  661. #endif /* bsd4 */
  662.  
  663.     execl(shpath,shname,"-c",comand,(char *)NULL); /* Execute the cmd */
  664.     exit(0);            /* just punt if it failed. */
  665.     } else if (pid == -1) {
  666.     debug(F100,"zxcmd fork failure","",0);
  667.     return(0);
  668.     }
  669.     close(pipes[1]);            /* don't need the output side */
  670.     fp[ZIFILE] = fdopen(pipes[0],"r");    /* open a stream for it */
  671.     fp[ZSYSFN] = fp[ZIFILE];        /* Remember. */
  672.     return(1);
  673. }
  674.  
  675. /*  Z C L O S F  - wait for the child fork to terminate and close the pipe. */
  676.  
  677. zclosf() {
  678.     int wstat;
  679.     if (kill(pid,9) == 0) {
  680.     debug(F101,"zclosf pid =","",pid);
  681.         while ((wstat = wait((int *)0)) != pid && wstat != -1) ;
  682.         pid = 0;
  683.     }
  684. #ifdef MINIX
  685. /* MINIX needs to wait() for zombies, or memory will not be reallocated */
  686.     else 
  687.     while(wait(0) >= 0) ;
  688. #endif
  689.  
  690.     fclose(fp[ZIFILE]);
  691.     fp[ZIFILE] = fp[ZSYSFN] = NULL;
  692.     return(1);
  693. }
  694.  
  695. /*  Z X P A N D  --  Expand a wildcard string into an array of strings  */
  696. /*
  697.   Returns the number of files that match fn1, with data structures set up
  698.   so that first file (if any) will be returned by the next znext() call.
  699. */
  700. zxpand(fn) char *fn; {
  701.     fcount = fgen(fn,mtchs,MAXWLD);    /* Look up the file. */
  702.     if (fcount > 0) {
  703.     mtchptr = mtchs;        /* Save pointer for next. */
  704.     }
  705.     debug(F111,"zxpand",mtchs[0],fcount);
  706.     return(fcount);
  707. }
  708.  
  709.  
  710. /*  Z N E X T  --  Get name of next file from list created by zxpand(). */
  711. /*
  712.  Returns >0 if there's another file, with its name copied into the arg string,
  713.  or 0 if no more files in list.
  714. */
  715. znext(fn) char *fn; {
  716.     if (fcount-- > 0) strcpy(fn,*mtchptr++);
  717.     else *fn = '\0';
  718.     debug(F111,"znext",fn,fcount+1);
  719.     return(fcount+1);
  720. }
  721.  
  722.  
  723. /*  Z N E W N  --  Make a new name for the given file  */
  724.  
  725. znewn(fn,s) char *fn, **s; {
  726. #ifdef BSD4
  727.     static char buf[256];
  728. #else
  729.     static char buf[100];
  730. #endif
  731.     char *bp, *xp;
  732.     int len = 0, n = 0, d = 0, t, i, power = 1;
  733. #ifdef MAXNAMLEN
  734.     int max = MAXNAMLEN;
  735. #else
  736.     int max = 14;
  737. #endif
  738.     bp = buf;
  739.     while (*fn) {            /* Copy name into buf */
  740.     *bp++ = *fn++;
  741.     len++;
  742.     }
  743.     if (len > max-2) {             /* Don't let it get too long */
  744.     bp = buf + max-2;
  745.     len = max - 2;
  746.     }
  747.     
  748.     for (i = 1; i < 4; i++) {        /* Try up to 999 times */
  749.     power *= 10;
  750.     *bp++ = '*';            /* Put a star on the end */
  751.     *bp-- = '\0';
  752.     
  753.     n = zxpand(buf);        /* Expand the resulting wild name */
  754.  
  755.     while (n-- > 0) {        /* Find any existing name~d files */
  756.         xp = *mtchptr++;
  757.         xp += len;
  758.         if (*xp == '~') {
  759.         t = atoi(xp+1);
  760.         if (t > d) d = t;    /* Get maximum d */
  761.         }
  762.     }
  763.     if (d < power-1) {
  764.         sprintf(bp,"~%d",d+1);    /* Make name~(d+1) */
  765.         *s = buf;
  766.         return;
  767.     }
  768.     bp--; len--;
  769.     }
  770. /* If we ever get here, we'll overwrite the xxx~100 file... */
  771. }
  772.  
  773. /* Directory Functions for Unix, written by Jeff Damens, CUCCA, 1984. */
  774.  
  775. /*
  776.  * The path structure is used to represent the name to match.
  777.  * Each slash-separated segment of the name is kept in one
  778.  * such structure, and they are linked together, to make
  779.  * traversing the name easier.
  780.  */
  781.  
  782. struct path {
  783.               char npart[MAXNAMLEN];    /* name part of path segment */
  784.               struct path *fwd;        /* forward ptr */
  785.             };
  786.  
  787. #ifdef PROVX1
  788. #define SSPACE 500
  789. #else
  790. #ifdef BSD29
  791. #define SSPACE 500
  792. #else
  793. #ifdef aegis
  794. #define SSPACE 10000            /* size of string-generating buffer */
  795. static char bslash;            /* backslash character if active */
  796. #else
  797. #define SSPACE 2000            /* size of string-generating buffer */
  798. #endif
  799. #endif
  800. #endif
  801. static char sspace[SSPACE];             /* buffer to generate names in */
  802. static char *freeptr,**resptr;             /* copies of caller's arguments */
  803. static int remlen;                      /* remaining length in caller's array*/
  804. static int numfnd;                      /* number of matches found */
  805.  
  806. /*
  807.  * splitpath:
  808.  *  takes a string and splits the slash-separated portions into
  809.  *  a list of path structures.  Returns the head of the list.  The
  810.  *  structures are allocated by malloc, so they must be freed.
  811.  *  Splitpath is used internally by the filename generator.
  812.  *
  813.  * Input: A string.
  814.  * Returns: A linked list of the slash-separated segments of the input.
  815.  */
  816.  
  817. struct path *
  818. splitpath(p)
  819. char *p;
  820. {
  821.  struct path *head,*cur,*prv;
  822.  int i;
  823.  head = prv = NULL;
  824.  if (*p == '/') p++;            /* skip leading slash */
  825.  while (*p != '\0')
  826.  {
  827.    cur = (struct path *) malloc(sizeof (struct path));
  828.    debug(F101,"splitpath malloc","",cur);
  829.    if (cur == NULL) fatal("malloc fails in splitpath()");
  830.    cur -> fwd = NULL;
  831.    if (head == NULL) head = cur;
  832.    else prv -> fwd = cur;       /* link into chain */
  833.    prv = cur;
  834. #ifdef aegis
  835.    /* treat backslash as "../" */
  836.    if (bslash && *p == bslash) {
  837.      strcpy(cur->npart, "..");
  838.      ++p;
  839.    } else {
  840.      for (i=0; i < MAXNAMLEN && *p && *p != '/' && *p != bslash; i++)
  841.        cur -> npart[i] = *p++;
  842.      cur -> npart[i] = '\0';      /* end this segment */
  843.      if (i >= MAXNAMLEN) while (*p && *p != '/' && *p != bslash) p++;
  844.    }
  845.    if (*p == '/') p++;
  846. #else
  847.    for (i=0; i < MAXNAMLEN && *p != '/' && *p != '\0'; i++)
  848.      cur -> npart[i] = *p++;
  849.    cur -> npart[i] = '\0';      /* end this segment */
  850.    if (i >= MAXNAMLEN) while (*p != '/' && *p != '\0') p++;
  851.    if (*p == '/') p++;
  852. #endif
  853.  }
  854.  return(head);
  855. }
  856.  
  857. /*
  858.  * fgen:
  859.  *  This is the actual name generator.  It is passed a string,
  860.  *  possibly containing wildcards, and an array of character pointers.
  861.  *  It finds all the matching filenames and stores them into the array.
  862.  *  The returned strings are allocated from a static buffer local to
  863.  *  this module (so the caller doesn't have to worry about deallocating
  864.  *  them); this means that successive calls to fgen will wipe out
  865.  *  the results of previous calls.  This isn't a problem here
  866.  *  because we process one wildcard string at a time.
  867.  *
  868.  * Input: a wildcard string, an array to write names to, the
  869.  *        length of the array.
  870.  * Returns: the number of matches.  The array is filled with filenames
  871.  *          that matched the pattern.  If there wasn't enough room in the
  872.  *        array, -1 is returned.
  873.  * By: Jeff Damens, CUCCA, 1984.
  874.  */
  875.  
  876. fgen(pat,resarry,len)
  877. char *pat,*resarry[];
  878. int len;
  879. {
  880.  struct path *head;
  881.  char scratch[100],*sptr;
  882. #ifdef aegis
  883.  char *getenv(), *index(), *namechars;
  884.  int tilde = 0, bquote = 0;
  885.  
  886.  if ((namechars = getenv("NAMECHARS")) != NULL) {
  887.   if (index(namechars, '~' ) != NULL) tilde  = '~';
  888.   if (index(namechars, '\\') != NULL) bslash = '\\';
  889.   if (index(namechars, '`' ) != NULL) bquote = '`';
  890.  }
  891.  else { tilde = '~'; bslash = '\\'; bquote = '`'; }
  892.  
  893.  sptr = scratch;
  894.  /* copy "`node_data", etc. anchors */
  895.  if (bquote && *pat == bquote)
  896.   while (*pat && *pat != '/' && *pat != bslash)
  897.    *sptr++ = *pat++;
  898.  else if (tilde && *pat == tilde)
  899.   *sptr++ = *pat++;
  900.  while (*pat == '/')
  901.   *sptr++ = *pat++;
  902.  if (sptr == scratch)
  903.  {
  904.   strcpy(scratch,"./");
  905.   sptr = scratch+2;
  906.  }                    /* init buffer correctly */
  907.  head = splitpath(pat);
  908. #else
  909.  head = splitpath(pat);
  910.  if (*pat == '/')
  911.  {
  912.   scratch[0] = '/';
  913.   sptr = scratch+1;
  914.  }
  915.  else
  916.  {
  917.   strcpy(scratch,"./");
  918.   sptr = scratch+2;
  919.  }                    /* init buffer correctly */
  920. #endif
  921.  numfnd = 0;                            /* none found yet */
  922.  freeptr = sspace;            /* this is where matches are copied */
  923.  resptr = resarry;            /* static copies of these so*/
  924.  remlen = len;                /* recursive calls can alter them */
  925.  traverse(head,scratch,sptr);        /* go walk the directory tree */
  926.  for (; head != NULL; head = head -> fwd)
  927.    free(head);                /* return the path segments */
  928.  return(numfnd);            /* and return the number of matches */
  929. }
  930.  
  931. /* traverse:
  932.  *  Walks the directory tree looking for matches to its arguments.
  933.  *  The algorithm is, briefly:
  934.  *   If the current pattern segment contains no wildcards, that
  935.  *   segment is added to what we already have.  If the name so far
  936.  *   exists, we call ourselves recursively with the next segment
  937.  *   in the pattern string; otherwise, we just return.
  938.  *
  939.  *   If the current pattern segment contains wildcards, we open the name
  940.  *   we've accumulated so far (assuming it is really a directory), then read
  941.  *   each filename in it, and, if it matches the wildcard pattern segment, add
  942.  *   that filename to what we have so far and call ourselves recursively on the
  943.  *   next segment.
  944.  *
  945.  *   Finally, when no more pattern segments remain, we add what's accumulated
  946.  *   so far to the result array and increment the number of matches.
  947.  *
  948.  * Input: a pattern path list (as generated by splitpath), a string
  949.  *      pointer that points to what we've traversed so far (this
  950.  *      can be initialized to "/" to start the search at the root
  951.  *      directory, or to "./" to start the search at the current
  952.  *      directory), and a string pointer to the end of the string
  953.  *      in the previous argument.
  954.  * Returns: nothing.
  955.  */
  956. traverse(pl,sofar,endcur)
  957. struct path *pl;
  958. char *sofar,*endcur;
  959. {
  960. #ifdef BSD42
  961.  DIR *fd, *opendir();
  962.  struct direct *dirbuf;
  963. #else
  964. #ifdef BSD29
  965.  DIR *fd, *opendir();
  966.  struct direct *dirbuf;
  967. #else
  968.  int fd;
  969.  struct direct dir_entry;
  970.  struct direct *dirbuf = &dir_entry;
  971. #endif
  972. #endif
  973.  struct stat statbuf;
  974.  if (pl == NULL)
  975.  {
  976.   *--endcur = '\0';                    /* end string, overwrite trailing / */
  977.   addresult(sofar);
  978.   return;
  979.  }
  980.  if (!iswild(pl -> npart))
  981.  {
  982.   strcpy(endcur,pl -> npart);
  983.   endcur += strlen(pl -> npart);
  984.   *endcur = '\0';                         /* end current string */
  985.   if (stat(sofar,&statbuf) == 0)    /* if current piece exists */
  986.   {
  987.       *endcur++ = '/';                  /* add slash to end */
  988.       *endcur = '\0';            /* and end the string */
  989.       traverse(pl -> fwd,sofar,endcur);
  990.   }
  991.   return;
  992.  }
  993. /* cont'd... */
  994.  
  995. /*...traverse, cont'd */
  996.  
  997. /* segment contains wildcards, have to search directory */
  998.  *endcur = '\0';                            /* end current string */
  999.  if (stat(sofar,&statbuf) == -1) return;       /* doesn't exist, forget it */
  1000.  if ((statbuf.st_mode & S_IFDIR) == 0) return;  /* not a directory, skip */
  1001. #ifdef BSD42            /* ==BSD4 */
  1002.  if ((fd = opendir(sofar)) == NULL) return;      /* can't open, forget it */
  1003.  while (dirbuf = readdir(fd))
  1004. #else
  1005. #ifdef BSD29            /* ==BSD29 */
  1006.  if ((fd = opendir(sofar)) == NULL) return;      /* can't open, forget it */
  1007.  while (dirbuf = readdir(fd))
  1008. #else
  1009.  
  1010.  if ((fd = open(sofar,O_RDONLY)) < 0) return;      /* can't open, forget it */
  1011.  while ( read(fd,dirbuf,sizeof dir_entry) )
  1012. #endif
  1013. #endif
  1014. {
  1015.   strncpy(nambuf,dirbuf->d_name,MAXNAMLEN); /* Get a null terminated copy!!! */
  1016.   nambuf[MAXNAMLEN] = '\0';
  1017.   if (dirbuf->d_ino != 0 && match(pl -> npart,nambuf)) {
  1018.     char *eos;
  1019.     strcpy(endcur,nambuf);
  1020.     eos = endcur + strlen(nambuf);
  1021.     *eos = '/';                    /* end this segment */
  1022.     traverse(pl -> fwd,sofar,eos+1);
  1023.   }
  1024. }
  1025. #ifdef BSD42            /* ==BSD4 */
  1026.  closedir(fd);
  1027. #else
  1028. #ifdef BSD29
  1029.  closedir(fd);
  1030. #else
  1031.  close(fd);
  1032. #endif
  1033. #endif
  1034. }
  1035.  
  1036. /*
  1037.  * addresult:
  1038.  *  Adds a result string to the result array.  Increments the number
  1039.  *  of matches found, copies the found string into our string
  1040.  *  buffer, and puts a pointer to the buffer into the caller's result
  1041.  *  array.  Our free buffer pointer is updated.  If there is no
  1042.  *  more room in the caller's array, the number of matches is set to -1.
  1043.  * Input: a result string.
  1044.  * Returns: nothing.
  1045.  */
  1046.  
  1047. addresult(str)
  1048. char *str;
  1049. {
  1050.  int l;
  1051.  if (strncmp(str,"./",2) == 0) str += 2;
  1052.  if (--remlen < 0) {
  1053.   numfnd = -1;
  1054.   return;
  1055.  }
  1056.  l = strlen(str) + 1;            /* size this will take up */
  1057.  if ((freeptr + l) > &sspace[SSPACE-1]) {
  1058.     numfnd = -1;            /* do not record if not enough space */
  1059.     return;
  1060.   }
  1061.  strcpy(freeptr,str);
  1062.  *resptr++ = freeptr;
  1063.  freeptr += l;
  1064.  numfnd++;
  1065. }
  1066.  
  1067. iswild(str)
  1068. char *str;
  1069. {
  1070.  char c;
  1071.  while ((c = *str++) != '\0')
  1072.    if (c == '*' || c == '?') return(1);
  1073.  return(0);
  1074. }
  1075.  
  1076. /*
  1077.  * match:
  1078.  *  pattern matcher.  Takes a string and a pattern possibly containing
  1079.  *  the wildcard characters '*' and '?'.  Returns true if the pattern
  1080.  *  matches the string, false otherwise.
  1081.  * by: Jeff Damens, CUCCA
  1082.  *
  1083.  * Input: a string and a wildcard pattern.
  1084.  * Returns: 1 if match, 0 if no match.
  1085.  */
  1086.  
  1087. match(pattern,string) char *pattern,*string; {
  1088.     char *psave,*ssave;            /* back up pointers for failure */
  1089.     psave = ssave = NULL;
  1090.     while (1) {
  1091.     for (; *pattern == *string; pattern++,string++)  /* skip first */
  1092.         if (*string == '\0') return(1);    /* end of strings, succeed */
  1093.     if (*string != '\0' && *pattern == '?') {
  1094.         pattern++;            /* '?', let it match */
  1095.         string++;
  1096.     } else if (*pattern == '*') {    /* '*' ... */
  1097.         psave = ++pattern;        /* remember where we saw it */
  1098.         ssave = string;        /* let it match 0 chars */
  1099.     } else if (ssave != NULL && *ssave != '\0') {    /* if not at end  */
  1100.                       /* ...have seen a star */
  1101.         string = ++ssave;        /* skip 1 char from string */
  1102.         pattern = psave;        /* and back up pattern */
  1103.     } else return(0);        /* otherwise just fail */
  1104.     }
  1105. }
  1106.  
  1107.